<template>
  <div class="production-table" id="SopTableID">
    <div class="table-title">
      <general-button
        @operation="ImportFun"
        btnText="导入模板"
        btnPowerNum="75527CF7-3E0A-4621-B1A7-784305C198A9"
      ></general-button>
      <general-button
        @operation="DownloadFun"
        btnText="导出模板"
        btnPowerNum="D04A9A9C-125F-4AFD-921C-9BCA5CCA8C8B"
      ></general-button>
      <general-button
        @operation="importImgFun"
        btnText="导入图片"
        btnPowerNum="F8FD7797-6C10-49F2-8335-88C9F06AEA38"
      ></general-button>
      <general-button
        @operation="downloadCheckImg"
        btnText="查看图片"
        btnPowerNum="F8FD7797-6C10-49F2-8335-88C9F06AEA38"
      ></general-button>
      <general-button
        @operation="addsopFun"
        btnText="添加"
        btnPowerNum="52BD8DC5-70FD-4B76-BF57-3C2AA9C685EF"
        :btnDisabled="!topcurrentInfo.RouteOperationID ? true : false"
      ></general-button>
      <general-button
        @operation="allDel"
        btnText="批量删除"
        btnPowerNum="5D21BA7E-35AA-4F2E-B201-B8BFFEEF6764"
        :btnDisabled="!topcurrentInfo.RouteOperationID ? true : false"
      ></general-button>
    </div>
    <div class="table-box">
      <a-table
        className="components-table-demo-nested"
        :columns="sopColumns"
        :row-key="(record) => record.OperationSOPID"
        :data-source="sopData"
        :loading="sopLoading"
        :scroll="{ y: sopTableHegint }"
        :row-selection="{
          selectedRowKeys: sopRowKeys,
          onChange: sopChangeFun,
        }"
        :pagination="false"
        size="middle"
        :customRow="rowClick"
        :rowClassName="setRowClassName"
      >
        <template slot="name" slot-scope="name">
          {{ name }}
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="chart-manage">
            <a-icon
              type="edit"
              class="icon-class"
              @click="editSopFun(record)"
            />
            <a-icon type="delete" class="icon-class" @click="Del(record)" />
          </div>
        </template>
      </a-table>
    </div>
    <!-- 导入文件弹窗 -->

    <!-- 导入文件弹窗 -->
    <a-modal
      v-model="sopannexModel"
      title="上传文件"
      :maskClosable="false"
      @cancel="sopmouldCancel"
    >
      <a-upload
        name="file"
        :multiple="true"
        :headers="headers"
        :file-list="sopfileList"
        :before-upload="beforeUpload"
        :remove="removeFun"
        accept=".xlsx,.xls"
      >
        <a-button :disabled="sopfileList.length != 0">
          <a-icon type="upload" />
          上传Excel文件
        </a-button>
      </a-upload>
      <template slot="footer">
        <a-button key="back" @click="sopmouldCancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="sopbuttonLoading"
          @click="sopannexOk"
          >提交</a-button
        >
      </template>
    </a-modal>
    <!-- 导入文件弹窗 -->

    <!-- 导入图片弹窗 Start -->
    <a-modal
      v-model="soppngModel"
      title="上传图片"
      :maskClosable="false"
      @cancel="sopPngCancel"
    >
      <div style="display: flex">
        <img style="height: 6.375rem; width: 6.375rem" alt="" v-if="isCheck" />
        <a-upload
          list-type="picture-card"
          :file-list="sopimgList"
          :before-upload="beforeUploadSopimg"
          @preview="handlePreview"
          :remove="removeSopimg"
        >
          <div v-if="sopimgList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传图片</div>
          </div>
        </a-upload>
        <a-modal
          :visible="previewVisible"
          :footer="null"
          @cancel="previewVisible = false"
          ><img alt="example" style="width: 100%" :src="previewImage"
        /></a-modal>
      </div>
      <template slot="footer">
        <a-button key="back" @click="sopPngCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="sopPngAdd">提交</a-button>
      </template>
    </a-modal>
    <!-- 导入图片弹窗 End -->

    <!-- 查看图片 -->
    <div class="check-img-box" v-if="previewVisibleImg">
      <div
        class="masking-out-box"
        @mouseenter="maskingShow = true"
        @mouseleave="maskingShow = false"
        @mousewheel.prevent="rollImg"
        @mousedown.prevent="moveImg"
        @dragstart.prevent
        ref="MASKING"
      >
        <div
          class="masking-out"
          v-show="maskingShow"
          ref="IMGMODAL"
          @mousedown.prevent="moveImg"
        >
          <a-icon type="delete" class="masking-icon" @click="deleteImg" />
          <a-icon
            type="close"
            class="masking-closeicon"
            @click="previewVisibleImg = false"
          />
        </div>
        <img
          alt="example"
          style="width: 100%"
          :src="previewImages"
          @mousedown.prevent="moveImg"
          ref="image"
        />
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { getSop } from "@/api/router-manage/index";
import {
  delOperationSOP,
  soptemplateDownload,
  sopImport,
  getEnclosureList,
  downloadEnclosure,
  delEnclosureRelation,
} from "@/api/route-operation/index";
import { CommonUploadFile } from "@/api/Common/index";
import { getTableScroll } from "@/common/table-calc";
import GeneralButton from "@/components/be-current-btn.vue";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
const reader = new FileReader();
//工序列表
const sopColumns = [
  {
    title: "序号",
    dataIndex: "num",
    sorter: true,
    width: "8%",
    align: "center",
  },
  {
    title: "工艺步骤",
    dataIndex: "SOPStep",
    width: "25%",
    scopedSlots: { customRender: "name" },
    align: "center",
  },
  {
    title: "过程描述",
    dataIndex: "OperationPoint",
    width: "25%",
    align: "center",
  },
  {
    title: "注意事项",
    dataIndex: "SOPAttention",
    width: "25%",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "operate",
    width: "15%",
    align: "center",
    scopedSlots: { customRender: "action" },
  },
]; //SOP表头数据
export default {
  props: ["RouteID", "topcurrentInfo", "technoLogyInfo"], //工艺id，选中表格工序项信息，选中工艺信息
  components: {
    GeneralButton,
  },
  data() {
    return {
      sopTableHegint: 0, //SOP表格高度
      isCheck: false, //点击的是查看图片还是上传图片
      sopimgList: [], //上传图片列表
      previewImage: "", //上传的图片预览链接
      previewVisible: false, //上传图片预览的状态控制
      soppngModel: false, //上传图片模态框
      sopLoading: false, //序号表格loading
      sopColumns, //序号表头
      sopRowKeys: [], //序号选中id
      sopData: [], //SOP列表信息
      sopselectedRow: [], //序号选中项
      sopannexModel: false, //导入文件弹窗
      sopbuttonLoading: false, //导入文件按钮Loading
      previewVisibleImg: false, //查看图片状态框,
      previewImages: null, //查看图片链接
      maskingShow: false, //移上图片蒙版显示
      enclosureID: "", //当前文件id
      headers: {
        authorization: "authorization-text",
      }, //上传文件格式
      sopfileList: [], //附件上传存储
      formData: "", //选择的文件信息
      currentRow: {}, //SOP当前选中
      rowClick: (record, index) => {
        return {
          on: {
            click: () => {
              this.currentRow = record;
              // this.$emit("currentInfo", this.currentRow);
            },
          },
        };
      }, //表格单行点击
    };
  },
  methods: {
    //点击表格
    setRowClassName(record, index) {
      return record.OperationSOPID == this.currentRow.OperationSOPID
        ? "clickRowStyl"
        : ""; //
    },
    //导入图片
    importImgFun() {
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作导入图片");
      this.isCheck = false;
      this.sopimgList = [];
      this.soppngModel = true;
    },
    //查看图片
    async downloadCheckImg() {
      let res = await getEnclosureList(this.RouteID);

      if (res.Data[0]) {
        let { EnclosureID } = res.Data[0];
        this.enclosureID = EnclosureID;
        let EnclosureRes = await downloadEnclosure(EnclosureID);
        if (EnclosureRes.Data.FilebyteStr) {
          this.previewImages = `data:image/png;base64,${EnclosureRes.Data.FilebyteStr}`;
          this.isCheck = true;
          this.previewVisibleImg = true;
        }
      } else {
        this.$message.info("暂无查询到该项有添加图片,请重新添加");
      }
    },
    //删除图片
    deleteImg() {
      let that = this;
      let { OperationSOPID } = this.currentRow;
      this.$confirm({
        title: `确认要删除该图片嘛？`,
        okText: "确认",
        okType: "danger",
        cancelText: "取消",
        async onOk() {
          const res = await delEnclosureRelation([
            {
              relationTableID: OperationSOPID,
              enclosureID: that.enclosureID,
            },
          ]);
          if (res.Data == "") {
            that.$message.info("删除成功");
            that.previewVisibleImg = false;
            that.previewImages = null;
          } else {
            that.$message.error(res.Data);
          }
          that.popUp();
        },
        onCancel() {},
      });
    },
    rollImg(e) {
      let image = this.$refs.image;
      let masking = this.$refs.MASKING;
      let IMGMODAL = this.$refs.IMGMODAL;
      let transform = image.style.transform;
      let zoom =
        transform.indexOf("scale") != -1
          ? +transform.split("(")[1].split(")")[0]
          : 1;
      zoom += e.wheelDelta / 1200;
      if (zoom > 0.1 && zoom < 2) {
        image.style.transform = "scale(" + zoom + ")";
        masking.style.transform = "scale(" + zoom + ")";
        IMGMODAL.style.transform = "scale(" + zoom + ")";
      }
    },

    moveImg(e) {
      let x = e.clientX;
      let y = e.clientY;
      document.onmouseup = () => {
        document.onmousemove = null;
      };
    },
    //阻止默认上传
    beforeUploadSopimg(file, fileList) {
      const isLt50M = file.size / 1024 / 1024 < 50;
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      return new Promise((resolve, reject) => {
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          if (isLt50M && isJpgOrPng) {
            file.thumbUrl = e.target.result;
            this.sopimgList = [...this.sopimgList, file];
            return false; // 阻止自动上传动作
          } else {
            this.sopimgList = [];
            message.error("请检查图片格式和大小!");
            reject(file);
          }
        };
        reader.onerror = (error) => reject(error);
      });
    },
    //点击预览图片值
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    //删除已上传图片
    removeSopimg(file) {
      this.sopimgList = [];
    },
    //上传excel附件
    beforeUpload(file) {
      return new Promise(async (resolve, reject) => {
        const arr = file.name.split(".");
        //限定只能取.xlxs || xls格式文件
        if (
          (arr[arr.length - 1] !== "xlsx" || arr[arr.length - 1] === "xls") &&
          (arr[arr.length - 1] === "xsls" || arr[arr.length - 1] !== "xls")
        ) {
          this.$message.warning("请上传Excel文件");
          return;
        }
        this.sopfileList = [...this.sopfileList, file];
        let formData = new FormData();
        formData.append("File", this.sopfileList[0]);
        this.formData = formData;
        return reject(false); //加上这个就会阻止默认上传
      });
    },
    //导入文件的删除
    removeFun() {
      this.sopfileList = [];
    },
    //上传附件时的删除
    annexRemove() {
      this.sopfileList = [];
    },
    //提交上传文件
    async sopannexOk() {
      const res = await sopImport(this.formData);
      if (res.Data != "") {
        this.$message.info("新增成功");
        const obj = {
          RouteID: this.RouteID,
          StdOperationID: this.StdOperationID,
          IndexNo: this.topcurrentInfo.IndexNo,
        };
        this.getSopFun(obj);
        this.sopannexModel = false;
      } else {
        this.$message.error(res.Data);
      }
    },
    //取消上传文件
    sopmouldCancel() {
      this.sopfileList = [];
      this.sopannexModel = false;
    },
    //新增图片
    async sopPngAdd() {
      let formData = new FormData();
      formData.append("File", this.sopimgList[0]);
      formData.append("FileType", 2);
      formData.append("RelationTableId", this.RouteID);
      formData.append("EnclosureTypeName", "其他附件");
      let res = await CommonUploadFile(formData);

      if (res.Data == "") {
        this.$message.info("导入成功");
        const obj = {
          RouteID: this.RouteID,
          StdOperationID: this.topcurrentInfo.StdOperationID,
          IndexNo: this.topcurrentInfo.IndexNo,
        };
        this.getSopFun(obj);
        this.sopimgList = [];
        this.soppngModel = false;
      } else {
        this.$message.error(res.Data);
      }
    },
    //取消上传图片
    sopPngCancel() {
      this.sopimgList = [];
      this.soppngModel = false;
    },
    //添加SOP弹窗
    addsopFun(value) {
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作");
      this.$emit("modalFun", {
        show: true,
        isEdit: value ? true : false,
        data: value ? JSON.parse(JSON.stringify(value)) : {},
      });
    },
    //修改SOP
    editSopFun(value) {
      if (!this.hasPermission("4B626B3E-9F20-4619-BE56-0364579ACB2F")) return;
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作");
      this.$emit("modalFun", {
        show: true,
        isEdit: value ? true : false,
        data: value ? JSON.parse(JSON.stringify(value)) : {},
      });
    },
    //更新表格
    popUp() {
      const obj = {
        RouteID: this.RouteID,
        StdOperationID: this.topcurrentInfo.StdOperationID,
        IndexNo: this.topcurrentInfo.IndexNo,
      };
      this.getSopFun(obj);
    },
    //单项删除SOP
    Del(item) {
      if (!this.hasPermission("5D21BA7E-35AA-4F2E-B201-B8BFFEEF6764")) return;
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作删除");
      const that = this;
      this.$confirm({
        title: `确认要删除【${item.SOPStep}】嘛？`,
        okText: "确认",
        okType: "danger",
        cancelText: "取消",
        async onOk() {
          const res = await delOperationSOP([item]);
          if (res.Data == "") {
            that.$message.info("删除成功");
          } else {
            that.$message.error(res.Data);
          }
          that.popUp();
        },
        onCancel() {},
      });
    },
    //批量删除SOP
    allDel() {
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作删除");
      if (this.sopselectedRow.length <= 0)
        return this.$message.error("请先选中表格项再批量删除");
      const that = this;
      this.$confirm({
        title: `确认要批量删除【${that.sopselectedRow.length}】项嘛？`,
        okText: "确认",
        okType: "danger",
        cancelText: "取消",
        async onOk() {
          const res = await delOperationSOP(that.sopselectedRow);
          if (res.Data == "") {
            that.$message.info("删除成功");
            that.sopselectedRow = [];
            that.sopRowKeys = [];
          } else {
            that.$message.error(res.Data);
          }
          that.popUp();
        },
        onCancel() {},
      });
    },
    //下载模板
    async DownloadFun() {
      const res = await soptemplateDownload({ RouteID: this.RouteID });
      if (res.Data.FilebyteStr == null) return;
      var raw = window.atob(res.Data.FilebyteStr);
      var uInt8Array = new Uint8Array(raw.length);
      for (var i = 0; i < raw.length; i++) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      const blob = new Blob([uInt8Array], {
        type: "application/vnd.ms-exce",
      });
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.download = `${res.Data.Name}`;
      document.body.appendChild(link);
      link.click();
    },
    //上传文件弹窗弹出
    ImportFun() {
      if (this.technoLogyInfo.IsCheck)
        return this.$message.error("当前工艺已审核,请反审核后再操作上传模板");
      this.sopannexModel = true;
    },
    //序号选择处理
    sopChangeFun(selectedRowKeys, selectedRows) {
      this.sopselectedRow = selectedRows; //选中项信息
      this.sopRowKeys = selectedRowKeys; //选中项ID
    },
    //修改SOP信息
    Edit(value) {
      this.$emit("crafteditFun", { edit: true, data: value });
    },
    //查询SOP表格
    async getSopFun(item) {
      const res = await getSop(item);
      this.sopData = res.Data;
      this.sopData.map((item, index) => {
        item.num = index + 1;
      });
    },
  },
  computed: {
    //根据点击工序表格返回相对应信息查询SOP表格
    tableUp() {
      const obj = {
        RouteID: this.RouteID,
        StdOperationID: this.topcurrentInfo.StdOperationID,
        IndexNo: this.topcurrentInfo.IndexNo,
      };

      this.getSopFun(obj);
    },
    showIdFun: function () {
      //工艺id
      return this.RouteID;
    },
    topcurrentInfoFun: function () {
      //工序信息
      return this.topcurrentInfo;
    },
  },
  mounted() {},
  updated() {
    this.$nextTick(() => {
      this.sopTableHegint = getTableScroll(38, "SopTableID");
    });
  },
  //工艺id
  watch: {
    showIdFun: function (newValue) {},
    topcurrentInfoFun: function (newValue) {
      const obj = {
        RouteID: this.RouteID,
        StdOperationID: newValue.StdOperationID,
        IndexNo: this.topcurrentInfo.IndexNo,
      };
      this.currentRow = {};
      this.getSopFun(obj);
    },
  },
};
</script>

<style lang="less" scoped>
.production-table {
  height: 100%;
  -webkit-user-drag: none;
}
.check-img-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.masking-out-box {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 99;
}
.masking-out {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba(255, 255, 255, 0.6);
  z-index: 99;

  .masking-icon {
    cursor: pointer;
    position: absolute;
    left: 5%;
    top: 5%;
    font-size: 1.25rem;
  }
  .masking-closeicon {
    cursor: pointer;
    position: absolute;
    right: 5%;
    top: 5%;
    font-size: 1.25rem;
  }
}
.production-table {
  .table-title {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 0.625rem;
    button {
      margin-right: 1.25rem;
    }
    button :last-child {
      margin-right: 0;
    }
  }
}
/deep/ .clickRowStyl {
  background: #e6f7ff !important;
  color: #000000 !important;
}
</style>
